from pars import *
from yant import *
import gramloader
import Lexer

def test_1():
	g = Grammar()

        E    = NTSymbol('E')
        T    = NTSymbol('T')
        P    = NTSymbol('P')

        sum = TSymbol('+')
        mul = TSymbol('*')
        lb  = TSymbol('(')
        rb  = TSymbol(')')
        i   = TSymbol('i')
	
	g.addProduction( Production( E, [E, sum, T] ) )
	g.addProduction( Production( E, [T] ) )
	g.addProduction( Production( T, [T, mul, P] ) )
	g.addProduction( Production( T, [P] ) )
	g.addProduction( Production( P, [lb, E, rb] ) )
	g.addProduction( Production( P, [i] ) )
	
#	for s in g.first( yant.Symbol("E") ):
		#print s
	
	#m = g.getPrecedenceMatrix(yant.Symbol("E"))
	
	g.shiftReduce(E, [i, sum, i, Symbol("")])

def test_2():
  
        
        g = Grammar()

        E    = NTSymbol('E')
        T    = NTSymbol('T')
        P    = NTSymbol('P')

        sum = TSymbol('+')
        mul = TSymbol('*')
        lb  = TSymbol('(')
        rb  = TSymbol(')')
        i   = TSymbol('i')
	
	g.addProduction( Production( E, [E, sum, T], 'a1 + a3' ) )
	g.addProduction( Production( E, [T], 'a1' ) )
	g.addProduction( Production( T, [T, mul, P], 'a1 * a3' ) )
	g.addProduction( Production( T, [P], 'a1' ) )
	g.addProduction( Production( P, [lb, E, rb], 'a2' ) )
	g.addProduction( Production( P, [i], 'a1') )

        g.build(E)

        lex = StubLex( [(i, 10), (sum, '+'), (i, 15), (EOS, '')] )
        analyzer = SRAnalyzer(lex, g.f, g.g)
        analyzer.run()

def test_3():
    automata = Lexer.DeterministicAutomata()
    
    # eat spaces
    automata.addTransition(Lexer.State("s"), Lexer.State("s"), " ") # eat all spaces
    automata.addTransition(Lexer.State("s"), Lexer.State("s"), "\n") # eat all newlines
    automata.addTransition(Lexer.State("s"), Lexer.State("s"), "\t") # eat all tabs
    automata.addTransition(Lexer.State("s"), Lexer.State("^", True, True), "") # finish if eof
    
    # DIGIT
    automata.addTransition(Lexer.State("s"), Lexer.State("digit1"), "ANY_DIGIT")
    automata.addTransition(Lexer.State("digit1"), Lexer.State("digit1"), "ANY_DIGIT")
    automata.addTransition(Lexer.State("digit1"), Lexer.State("i", True, True), "ANY_SEPARATOR")
    
    # INCREMENT
    automata.addTransition(Lexer.State("s"), Lexer.State("+", True), "+")
    
    # INCREMENT
    automata.addTransition(Lexer.State("s"), Lexer.State("*", True), "*")
    
    lexer = Lexer.Lexer(automata, Lexer.BufferedReader("10 + 15 * 10") )
    
    g = gramloader.loadGrammar('simple.gram')

#     sum = TSymbol('+')
#     mul = TSymbol('*')
#     lb  = TSymbol('(')
#     rb  = TSymbol(')')
#     i   = TSymbol('i')

#     lex = StubLex( [(i, 10), (sum, '+'), (i, 15), (EOS, '')] )

    push_lexer = PushLexer(lexer)
    analyzer = SRAnalyzer(push_lexer, g.f, g.g)
    analyzer.run()
	
test_3()

